import { Component } from '../../../components/base-component';
import { ICar } from '../../../interfaces/car';

export class Car extends Component {
  private svgTag = document.createElementNS('http://www.w3.org/2000/svg', 'svg');

  private useTag = document.createElementNS('http://www.w3.org/2000/svg', 'use');

  private animation: Animation | null = null;

  constructor({ id, color, name }: ICar) {
    super({ className: 'svg-container' });
    this.svgTag.setAttributeNS(null, 'class', `${name}-${id} car`);
    this.svgTag.setAttributeNS(null, 'fill', `${color}`);
    this.useTag.setAttributeNS(
      'http://www.w3.org/1999/xlink',
      'xlink:href',
      `./assets/car.svg#car`
    );
    this.svgTag.append(this.useTag);
    this.getNode().append(this.svgTag);
  }

  animateCar(duration: number) {
    const width = window.innerWidth;
    this.animation = this.node.animate(
      [
        {
          transform: 'translateX(0)',
        },
        {
          transform: `translateX(${width - 167}px)`,
        },
      ],
      {
        duration,
        fill: 'forwards',
      }
    );
  }

  stopAnimation() {
    this.animation?.pause();
  }

  cancelAnimation() {
    this.animation?.cancel();
  }
}
